package com.bjbn.service.impl;

import com.alibaba.fastjson2.JSON;
import com.bjbn.dto.WalkwayStatusDto;
import com.bjbn.entity.BmsDeviceGroup;
import com.bjbn.mapper.BmsDeviceGroupMapper;
import com.bjbn.service.BaDeviceStateService;
import com.bjbn.service.WalkwayStatusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class WalkwayStatusServiceImpl implements WalkwayStatusService {

    @Autowired
    private BmsDeviceGroupMapper deviceGroupMapper;
    
    @Autowired
    private BaDeviceStateService baDeviceStateService;

    private static final String WALKWAY_TYPE = "步道梯";
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public List<WalkwayStatusDto> getAllWalkwayStatus() {
        List<WalkwayStatusDto> result = new ArrayList<>();
        
        try {
            // 查询所有步道梯设备
            List<BmsDeviceGroup> walkwayList = deviceGroupMapper.selectList(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<BmsDeviceGroup>()
                            .eq(BmsDeviceGroup::getDeviceType, WALKWAY_TYPE)
            );

            for (BmsDeviceGroup group : walkwayList) {
                try {
                    WalkwayStatusDto statusDto = buildWalkwayStatusDto(group);
                    if (statusDto != null) {
                        result.add(statusDto);
                    }
                    
                    // 避免请求过于频繁
                    Thread.sleep(50);
                    
                } catch (Exception e) {
                    log.error("查询步道梯{}状态异常", group.getDeviceNum(), e);
                }
            }
            
        } catch (Exception e) {
            log.error("查询所有步道梯状态异常", e);
        }
        
        return result;
    }

    @Override
    public WalkwayStatusDto getWalkwayStatusByDeviceNum(String deviceNum) {
        try {
            // 查询指定设备
            BmsDeviceGroup group = deviceGroupMapper.selectOne(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<BmsDeviceGroup>()
                            .eq(BmsDeviceGroup::getDeviceNum, deviceNum)
                            .eq(BmsDeviceGroup::getDeviceType, WALKWAY_TYPE)
            );
            
            if (group == null) {
                log.warn("未找到设备编码为{}的步道梯设备", deviceNum);
                return null;
            }
            
            return buildWalkwayStatusDto(group);
            
        } catch (Exception e) {
            log.error("查询步道梯{}状态异常", deviceNum, e);
            return null;
        }
    }
    
    /**
     * 构建步道梯状态DTO
     */
    private WalkwayStatusDto buildWalkwayStatusDto(BmsDeviceGroup group) {
        try {
            String deviceNum = group.getDeviceNum();
            
            // 调用BA接口获取实时状态
            String deviceValueData = baDeviceStateService.parseDeviceState(deviceNum);
            
            if (deviceValueData == null) {
                log.warn("设备{}状态解析失败", deviceNum);
                return null;
            }
            
            // 解析状态JSON
            Map<String, Object> statusMap = JSON.parseObject(deviceValueData, Map.class);
            
            WalkwayStatusDto statusDto = new WalkwayStatusDto();
            statusDto.setDeviceNum(deviceNum);
            statusDto.setDeviceName(group.getDeviceName());
            statusDto.setDownStatus(String.valueOf(statusMap.getOrDefault("下行", "0")));
            statusDto.setUpStatus(String.valueOf(statusMap.getOrDefault("上行", "0")));
            statusDto.setFaultStatus(String.valueOf(statusMap.getOrDefault("故障", "0")));
            statusDto.setStatusJson(deviceValueData);
            statusDto.setLastUpdateTime(sdf.format(new Date()));
            
            return statusDto;
            
        } catch (Exception e) {
            log.error("构建步道梯状态DTO异常，设备：{}", group.getDeviceNum(), e);
            return null;
        }
    }
} 